<?php
namespace frontend\models;

use common\models\User;
use yii\base\Model;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * Signup form
 * @property string[] $roles
 */
class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;
    public $first_name;
    public $last_name;
    public $roles;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => '用户名已被使用'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'Email地址已被使用'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],

            ['first_name', 'required', 'message' => '请填写您的姓氏'],
            ['first_name', 'string', 'min' => 1, 'max' => 50],

            ['last_name', 'required', 'message' => '请填写您的名字'],
            ['last_name', 'string', 'min' => 1, 'max' => 50],

            // This rule makes roles can be load into model
            ['roles', 'safe']
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate()) {
            $user = new User();
            $user->username = $this->username;
            $user->email = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->first_name = $this->first_name;
            $user->last_name = $this->last_name . '---' . json_encode($this->roles);
            $user->save(false);
            /*
            if ($user->save(false)) {
                return $user;
            }*/

            // Add the permissions to user
            $auth = Yii::$app->authManager;
            foreach ($this->roles as $item) {
                $role = $auth->getRole($item);
                $auth->assign($role, $user->id);
            }
            return $user;
        }
        return null;
    }
}
